//
//  ArmEditViewController.m
//  wAudioShare
//
//  Created by Anson on 14-11-11.
//  Copyright (c) 2014年 赵帅. All rights reserved.
//

#import "ArmEditViewController.h"
#import "ArmListViewCell.h"
#import "ArmModel.h"

@interface ArmEditViewController ()

@property (weak, nonatomic) IBOutlet UISwitch *swNotify;

@end

@implementation ArmEditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.title =@"条件";
    self.labelTitle.text = self.armData.label;
    [self.swNotify setOn:self.armData.notify];
    [self loadDeviceData];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Http Request
//!获取条件中的设备列表
-(void)loadDeviceData
{
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl) {

    [activity startAnimating];
    
    NSString *urlStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Cond.cgi?action=do_listvalue&cond=%ld", ipUrl, self.armData.armId];
    
    [Utitlity commonHTTPMethod:urlStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [activity stopAnimating];
        
        if (!responseObject) return;
        NSDictionary *retJsonData = responseObject;
        NSLog(@"%@", retJsonData);
        if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
            
            //!由于空调返回的数据项有2个(因为有温度另外一个，需要使用该变量临时存储方便搜索
            NSMutableDictionary *thermostatDevList = [NSMutableDictionary dictionaryWithCapacity:10];
            
            NSArray *devList = [retJsonData objectForKey:@"data"];
            for (NSDictionary *dict in devList)
            {
                for (NSInteger i=0; i<self.canSelectDeviceList.count; i++) {
                    
                    NSDictionary *item = [self.canSelectDeviceList objectAtIndex:i];
                    NSString *deviceId = item[@"ZID"];
                    if ([deviceId isEqualToString:dict[@"did"]]) {
                        
                        SceneDeviceModel *data = [[SceneDeviceModel alloc] init];
                        data.deviceId = deviceId;
                        data.deviceType = [item[@"DeviceType"] integerValue];
                        data.title = item[@"Alias"];
                        switch (data.deviceType) {
                            case SceneDeviceTypeBinarySensor:
                            case SceneDeviceTypeMultilevelSensor:
                            case SceneDeviceTypeSwitch:
                            case SceneDeviceTypeMotor:
                            case SceneDeviceTypePowerMeter:
                            case SceneDeviceTypeDoorLock:
                            {
                                data.isOn = [dict[@"value"] boolValue];
                                break;
                            }
                                
                            case SceneDeviceTypeDimmer:
                            {
                                data.isOn = YES;
                                data.percent = [dict[@"value"] integerValue];
                                break;
                            }
                            case SceneDeviceTypeThermostat:{
                                
                                SceneDeviceModel *thermostatDev = thermostatDevList[deviceId];
                                if (thermostatDev) {
                                    
                                    thermostatDev.thermostatTemperature = [dict[@"value"] integerValue];
                                    data = thermostatDev;
                                    
                                }else {
                                    
                                    data.mode = dict[@"value"];
                                    if (![data.mode.lowercaseString isEqualToString:@"off"]) {
                                        data.isOn = YES;
                                    }else
                                        break;
                                    
                                    if ([data.mode.lowercaseString isEqualToString:@"heat"] || [data.mode.lowercaseString isEqualToString:@"cool"]) {
                                        thermostatDevList[deviceId] = data;
                                        goto forbreak;
                                    }
                                }
                                
                                break;
                            }
                            default:
                                break;
                        }
                        [self.attachDeviceModelList addObject:data];
                        [self.canSelectDeviceList removeObjectAtIndex:i--];
                        break;
                        
                    forbreak: break;
                    }
                }
                
            }
            
            [self.attachDeviceListView reloadData];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [activity stopAnimating];
        NSLog(@"error:%@",error);
    }];
    }
}

//- (void)addNewArmDevice:(SceneDeviceModel *)deviceData type:(SceneDeviceType)type {
- (void)reqConfigSceneDevice:(NSString *)deviceZID {
    
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl) {

    NSString *urlBase = [NSString stringWithFormat:@"http://%@/cgi-bin/Cond.cgi?action=do_add&cond=%ld&did=%@", ipUrl, self.armData.armId, deviceZID];
    NSString *urlStr = nil;
    switch (_currentSelectDeviceType) {
        case SceneDeviceTypeBinarySensor:
        {
            urlStr = [urlBase stringByAppendingFormat:@"&cmd=48&index=0&value=%@", (self.addDeviceFunctionModel.isOn == YES ? @"True" : @"False")];
            break;
        }
                                                                                      
        case SceneDeviceTypeMultilevelSensor:
        {
            urlStr = [urlBase stringByAppendingFormat:@"&cmd=49&index=0&value=%@", @""];
            break;
        }
            
        case SceneDeviceTypeMotor:
        {
            urlStr = [urlBase stringByAppendingFormat:@"&cmd=38&index=0&value=%d", (self.addDeviceFunctionModel.isOn == YES ? 255 : 0)];
            break;
        }
            
        case SceneDeviceTypePowerMeter:
        case SceneDeviceTypeSwitch:
        {
            urlStr = [urlBase stringByAppendingFormat:@"&cmd=0x25&index=0&value=%d", (self.addDeviceFunctionModel.isOn == YES ? 255 : 0)];
            break;
        }
            
        case SceneDeviceTypeThermostat:
        {
            if (self.addDeviceFunctionModel.isOn) {
                urlStr = [urlBase stringByAppendingFormat:@"&cmd=0x40&index=0&value=%@", self.addDeviceFunctionModel.mode];
            }else
                urlStr = [urlBase stringByAppendingString:@"&cmd=0x40&index=0&value=Off"];
            break;
        }
            
        case SceneDeviceTypeDimmer:
        {
            if (self.addDeviceFunctionModel.percent == 100) self.addDeviceFunctionModel.percent = 99;
            
            urlStr = [urlBase stringByAppendingFormat:@"&cmd=0x26&index=0&value=%ld", self.addDeviceFunctionModel.percent];
            break;
        }

        case SceneDeviceTypeDoorLock:
        {
            urlStr = [urlBase stringByAppendingFormat:@"&cmd=0x62&index=0&value=%@", self.addDeviceFunctionModel.isOn == YES ? @"True": @"False"];
            break;
        }
        default:
            break;
    }
        if (_currentEditAttachedDevice) {
            [self sendReqConfigAttachDeviceWithURL:urlStr thermostateBaseUrl:urlBase];
        }else
            [self sendReqAddNewDeviceToSceneWithURL:urlStr thermostateBaseUrl:urlBase];
    }
        /*
    
    [Utitlity commonHTTPMethod:urlStr responseType:jsonType
                       success:^(AFHTTPRequestOperation *operation, id responseObject) {
                           [activity stopAnimating];
                           
                           if (!responseObject) return;
                           NSDictionary *retJsonData = responseObject;
                           if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
                               
                               if (self.addDeviceFunctionModel.deviceType == SceneDeviceTypeThermostat
                                   && self.addDeviceFunctionModel.isOn
                                   && ([self.addDeviceFunctionModel.mode.lowercaseString isEqualToString:@"heat"] || [self.addDeviceFunctionModel.mode.lowercaseString isEqualToString:@"cool"] )) {
                                   //发送设置空调温度请求
                                   NSString * urlThermostat = [urlBase stringByAppendingFormat:@"&cmd=0x43&index=%d&value=%ld", ([self.addDeviceFunctionModel.mode.lowercaseString isEqualToString:@"heat"]?1:2), self.addDeviceFunctionModel.thermostatTemperature];
                                   
                                   dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                                       
                                       [Utitlity commonHTTPMethod:urlThermostat responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
                                           
                                           if (!responseObject) return;
                                           NSDictionary *retJsonData = responseObject;
                                           if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
                                               
                                               [self.canSelectDeviceList removeObject:self.selectedDeviceItemData];
                                               [self.attachDeviceModelList addObject:self.addDeviceFunctionModel];
                                               [self reSetDevListSelect];
                                               [self.attachDeviceListView reloadData];
                                           }
                                           
                                       } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                           [activity stopAnimating];
                                           NSLog(@"error:%@",error);
                                           
                                       }];
                                   });
                                   
                               }else {
                  
                                   [self.canSelectDeviceList removeObject:self.selectedDeviceItemData];
                                   [self.attachDeviceModelList addObject:self.addDeviceFunctionModel];
                                   [self reSetDevListSelect];
                                   [self.attachDeviceListView reloadData];
                               }
                               
                           }
                           
                       } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                           [activity stopAnimating];
                           NSLog(@"error:%@",error);
                       }
     ];
    }
         */
}

//!删除条件已添加的某个设备
-(void)deleteAttachDevice:(SceneDeviceModel *)modelData{
    
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl) {

    [activity startAnimating];
    
    NSString *urlStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Cond.cgi?action=do_del&cond=%ld&did=%@", ipUrl, self.armData.armId, modelData.deviceId];
     
    [Utitlity commonHTTPMethod:urlStr responseType:jsonType
                       success:^(AFHTTPRequestOperation *operation, id responseObject) {
                           [activity stopAnimating];
                           
                           if (!responseObject) return;
                           NSDictionary *retJsonData = responseObject;
                           if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
                               
                               [self.attachDeviceModelList removeObject:modelData];
                               [self.attachDeviceListView reloadData];
                           }
                           
                       } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                           [activity stopAnimating];
                           NSLog(@"error:%@",error);
                       }
     ];
    
    [self.attachDeviceListView setEditing:!self.attachDeviceListView.editing animated:YES];
    }
}

//!设置通知
- (void)setArmEnableNotify:(BOOL)isEnable {
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl) {

    NSString *urlStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Cond.cgi?action=do_setflag&cond=%ld&notify=%@", ipUrl, self.armData.armId, (isEnable?@"True":@"False")];
    [Utitlity commonHTTPMethod:urlStr responseType:jsonType
                       success:^(AFHTTPRequestOperation *operation, id responseObject) {
                           [activity stopAnimating];
                           
                           if (!responseObject) return;
                           NSDictionary *retJsonData = responseObject;
                           if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
                               [self.swNotify setOn:isEnable animated:YES];
                           }else
                               [self.swNotify setOn:!isEnable];
                           
                       } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                           [activity stopAnimating];
                           NSLog(@"error:%@",error);
                       }
     ];
    }
}

#pragma mark - UIButton
- (IBAction)addNewDeviceToArm:(id)sender {
    
    [self reqConfigSceneDevice:self.addDeviceFunctionModel.deviceId];
    
}

- (IBAction)notificationSwitchValChanged:(UISwitch *)sender {
    
    [self setArmEnableNotify:sender.isOn];
}

#pragma mark - UITableView
- (void)pickerViewConfirmForFunctionList:(NSInteger)picker_selected_index {
    [super pickerViewConfirmForFunctionList:picker_selected_index];
    
    if (_currentEditAttachedDevice == YES) {
        [self reqConfigSceneDevice:self.addDeviceFunctionModel.deviceId];
    }
}

@end
